package com.kol.collect.interceptor;

/**
 * Created by liukun on 20/3/6.
 */

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.kol.collect.common.AjaxJson;
import com.kol.collect.common.util.TokenUtil;
import com.kol.collect.exception.BusinessException;

import io.jsonwebtoken.Claims;

@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {
    @Resource
    private TokenUtil tokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 地址过滤
        String uri = request.getRequestURI();
        if (uri.contains("/login")) {
            return true;
        }
        // Token 验证
        String token = request.getHeader(tokenUtil.getHeader());
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter(tokenUtil.getHeader());
        }
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(AjaxJson.STATUS_USER_LOGIN_NO_TOKEN, AjaxJson.MSG_USER_LOGIN_NO_TOKEN);
        }
        Claims claims = tokenUtil.getTokenClaim(token);
        if (claims == null || tokenUtil.isTokenExpired(claims.getExpiration())) {
            throw new BusinessException(AjaxJson.STATUS_TOKEN_FAIL, AjaxJson.MSG_TOKEN_FAIL);
        }
        // 设置 identityId 用户身份ID
        request.setAttribute("identityId", claims.getSubject());
        return true;
    }
}